<template>
  <!--
  难点:
  1. 双向数据绑定(期待数组)与查询参数(期待字符串)中对于 goods_cat 属性类型的冲突问题
  2. 处理 attrs 参数
  -->
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>新增商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片布局 -->
    <el-card>
      <el-alert title="添加商品信息" type="info" center show-icon> </el-alert>
      <!-- activeIndex - 0  传过来的值是一个字符串,这里需要接收数字,利用类数字型运算操作进行隐式转换 -->
      <el-steps :active="activeIndex - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!--

 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
        label-position="top"
      >
        <!-- activeIndex 通过name属性值来控制选中及联动进度条 -->
        <!-- :before-leave 接收一个函数(属性),控制 tab 栏的切换行为 -->
        <el-tabs
          v-model="activeIndex"
          tab-position="left"
          :before-leave="handelBeforLeave"
          @tab-click="handleTabClick"
        >
          <!-- <el-tab-pane> 只能作为 <el-tabs> 的子标签存在 -->
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <!-- 级联选择器 -->
              <el-cascader
                v-model="addForm.goods_cat"
                :options="cateList"
                :props="{
                  expandTrigger: 'hover',
                  label: 'cat_name',
                  value: 'cat_id',
                }"
                clearable
                @change="handleCascaderChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              :label="item.attr_name"
              v-for="item in manyTableData"
              :key="item.attr_id"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  :label="subItem"
                  v-for="(subItem, subIndex) in item.attr_vals"
                  :key="subIndex"
                  border
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :label="item.attr_name"
              v-for="item in onlyTableData"
              :key="item.attr_id"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- 图片上传组件 -->
            <!-- 该组件没有调用 axios 发起网络请求(故没有携带请求头,这里手动添加) -->
            <el-upload
              :action="uploadUrl"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headerObj"
              :on-success="handleSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <el-button type="primary" style="margin-top: 15px" @click="add"
              >添加商品</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 图片预览弹出层 -->
    <el-dialog title="预览" :visible.sync="previewDialogVisible" width="50%">
      <img :src="previewUrl" style="width: 100%" />
    </el-dialog>
  </div>
</template>

<script>
// 深拷贝依赖
import _ from 'lodash'
export default {
  data () {
    return {
      activeIndex: '0',
      // 添加商品表单
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: [],
        pics: [],
        // 商品简介
        goods_introduce: ''
      },
      // 分类列表
      cateList: [],
      // 添加商品验证规则
      addFormRules: {
        goods_name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        goods_price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
        goods_weight: [{ required: true, message: '请输入商品重量', trigger: 'blur' }],
        goods_number: [{ required: true, message: '请输入商品数量', trigger: 'blur' }],
        goods_cat: [{ required: true, message: '请选择商品分类', trigger: 'blur' }]
      },
      // 动态参数列表数据
      manyTableData: [],
      // 静态属性列表数据
      onlyTableData: [],
      // 图片上传的地址
      uploadUrl: 'http://127.0.0.1:8888/api/private/v1/upload',
      // 手动携带请求头
      headerObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 图片的网络地址
      previewUrl: '',
      previewDialogVisible: false
    }
  },
  created () {
    this.getCateList()
  },
  methods: {
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      this.cateList = res.data
    },
    handleCascaderChange () {
      // 只允许选中三级分类,否则清空数组
      if (this.addForm.goods_cat.length < 3) {
        this.addForm.goods_cat = []
      }
    },
    // 阻止 tab 栏的切换行为
    // activeName 将要去往的页面的 name
    // oldActiveName 从哪个页面出来
    handelBeforLeave (activeName, oldActiveName) {
      if (oldActiveName === '0' && this.addForm.goods_cat.length < 3) {
        this.$message.error('请先选择商品分类!')
        return false
      }
    },
    // 点击 tab 切换的时候发送请求
    async handleTabClick () {
      if (this.activeIndex === '1') {
        const { data: res } = await this.$http.get('categories/' + this.cateId + '/attributes', { params: { sel: 'many' } })
        res.data.forEach(t => {
          t.attr_vals = t.attr_vals ? t.attr_vals.split(' ') : []
        })
        this.manyTableData = res.data
      } else if (this.activeIndex === '2') {
        const { data: res } = await this.$http.get('categories/' + this.cateId + '/attributes', { params: { sel: 'only' } })
        this.onlyTableData = res.data
      }
    },
    // 点击图片预览触发函数
    handlePreview (file) {
      this.previewUrl = file.response.data.url
      this.previewDialogVisible = true
    },
    // 点击移除触发函数
    handleRemove (file) {
      // console.log(file)
      // 1.找到图片路径
      const tmpPhat = file.response.data.tmp_path
      // 2.拿到该路径在数组中的索引
      const index = this.addForm.pics.findIndex(t => t.pic === tmpPhat)
      // 3.删除改属性所在的对象
      this.addForm.pics.splice(index, 1)
    },
    // 保存图片的存放地址到 addForm 中
    handleSuccess (response) {
      this.addForm.pics.push({
        pic: response.data.tmp_path
      })
    },
    // 添加商品
    add () {
      this.$refs.addFormRef.validate(async valid => {
        if (valid) {
          // 用 _.colneDeep() 方法对 addForm 查询对象进行深拷贝
          // 解决双向数据绑定(期待数组)与查询参数(期待字符串)中对于 goods_cat 属性类型的冲突问题
          // 实际操作与上传的是深拷贝的那一份查询参数对象
          const formData = _.cloneDeep(this.addForm)
          formData.goods_cat = formData.goods_cat.join(',')
          formData.attrs = []

          this.manyTableData.forEach(t => {
            formData.attrs.push({
              attr_id: t.attr_id,
              attr_value: t.attr_vals.join(' ')
            })
          })
          this.onlyTableData.forEach(t => {
            formData.attrs.push({
              attr_id: t.attr_id,
              attr_value: t.attr_vals
            })
          })
          const { data: res } = await this.$http.post('goods', formData)
          if (res.meta.status === 201) {
            this.$message.success('添加成功!')
            this.$router.push('/goods')
          } else {
            this.$message.error('添加失败!')
          }
        } else {
          this.$message.error('请填写必要的表单数据!')
        }
      })
    }
  },
  computed: {
    cateId () {
      return this.addForm.goods_cat[this.addForm.goods_cat.length - 1]
    }
  }
}
</script>

<style lang="less" scoped>
.el-checkbox {
  margin: 0 10px 0 0;
}
</style>
